package com.demo.accessibilitykeeper;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.accessibility.AccessibilityManager;

import java.io.File;
import java.util.List;
import java.util.Random;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/9/23 18:04
 */
public class LauncherDatabaseManager {

    private static final String TAG = "LauncherDBManager";

    // 主流Launcher的数据库路径
    private static final String[] LAUNCHER_DB_PATHS = {
            "/data/data/com.android.launcher3/databases/launcher.db",
            "/data/data/com.sec.android.app.launcher/databases/launcher.db", // 三星
            "/data/data/com.miui.home/databases/launcher.db", // 小米
            "/data/data/com.huawei.android.launcher/databases/launcher.db", // 华为
            "/data/data/com.oppo.launcher/databases/launcher.db", // OPPO
            "/data/data/com.bbk.launcher2/databases/launcher.db" // VIVO
    };

    /**
     * 将应用移动到随机文件夹
     */
    public static boolean moveAppToRandomFolder(Context context, String packageName) {
        try {
            String launcherPackage = getLauncherPackage(context);
            String dbPath = getLauncherDatabasePath(launcherPackage);

            if (dbPath != null) {
                return moveAppInDatabase(dbPath, packageName, context);
            }

            // 如果数据库方法失败，尝试Intent方法
            return moveAppViaIntent(context, packageName);

        } catch (Exception e) {
            Log.e(TAG, "Failed to move app to folder", e);
            return false;
        }
    }

    /**
     * 获取当前Launcher包名
     */
    private static String getLauncherPackage(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);

        ResolveInfo resolveInfo = context.getPackageManager()
                .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);

        return resolveInfo != null ? resolveInfo.activityInfo.packageName : null;
    }

    /**
     * 获取Launcher数据库路径
     */
    private static String getLauncherDatabasePath(String launcherPackage) {
        for (String path : LAUNCHER_DB_PATHS) {
            if (path.contains(launcherPackage)) {
                File dbFile = new File(path);
                if (dbFile.exists()) {
                    return path;
                }
            }
        }
        return null;
    }

    /**
     * 在数据库中移动应用
     */
    private static boolean moveAppInDatabase(String dbPath, String packageName, Context context) {
        try {
            // 需要Root权限操作数据库
            if (!hasRootAccess()) {
                return moveAppViaAccessibility(context, packageName);
            }

            SQLiteDatabase db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);

            // 1. 创建随机文件夹
            long folderId = createRandomFolder(db, context);

            // 2. 移动应用到文件夹
            moveAppToFolder(db, packageName, folderId);

            // 3. 更新屏幕位置
            updateScreenPosition(db, folderId);

            db.close();

            // 4. 通知Launcher更新
            notifyLauncherUpdate(context);

            return true;

        } catch (Exception e) {
            Log.e(TAG, "Database operation failed", e);
            return false;
        }
    }

    /**
     * 创建随机文件夹
     */
    private static long createRandomFolder(SQLiteDatabase db, Context context) {
        String[] folderNames = {
                "工具", "游戏", "学习", "生活", "娱乐", "购物", "社交", "办公",
                "系统工具", "实用工具", "常用软件", "其他应用", "效率工具"
        };

        String randomName = folderNames[new Random().nextInt(folderNames.length)];

        ContentValues values = new ContentValues();
        values.put("title", randomName);
        values.put("itemType", 2); // 文件夹类型
        values.put("container", -100); // 桌面容器
        values.put("screen", getRandomScreen());
        values.put("cellX", new Random().nextInt(4));
        values.put("cellY", new Random().nextInt(5));
        values.put("spanX", 1);
        values.put("spanY", 1);

        return db.insert("favorites", null, values);
    }

    /**
     * 移动应用到文件夹
     */
    private static void moveAppToFolder(SQLiteDatabase db, String packageName, long folderId) {
        ContentValues values = new ContentValues();
        values.put("container", folderId);
        values.put("cellX", 0);
        values.put("cellY", 0);

        String whereClause = "intent LIKE ?";
        String[] whereArgs = {"%" + packageName + "%"};

        db.update("favorites", values, whereClause, whereArgs);
    }

    /**
     * 获取随机屏幕位置
     */
    private static int getRandomScreen() {
        return new Random().nextInt(3); // 0-2屏
    }

    /**
     * 更新屏幕位置
     */
    private static void updateScreenPosition(SQLiteDatabase db, long folderId) {
        ContentValues values = new ContentValues();
        values.put("screen", getRandomScreen());
        values.put("cellX", new Random().nextInt(4));
        values.put("cellY", new Random().nextInt(5));

        String whereClause = "_id = ?";
        String[] whereArgs = {String.valueOf(folderId)};

        db.update("favorites", values, whereClause, whereArgs);
    }

    /**
     * 通知Launcher更新
     */
    private static void notifyLauncherUpdate(Context context) {
        Intent intent = new Intent("com.android.launcher.action.APPWIDGET_UPDATE");
        context.sendBroadcast(intent);

        // 发送Launcher重载广播
        Intent reloadIntent = new Intent("android.intent.action.MAIN");
        reloadIntent.addCategory(Intent.CATEGORY_HOME);
        reloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(reloadIntent);
    }

    /**
     * 通过Intent移动应用
     */
    private static boolean moveAppViaIntent(Context context, String packageName) {
        try {
            // 发送创建文件夹的Intent
            Intent createFolderIntent = new Intent("android.intent.action.CREATE_SHORTCUT");
            createFolderIntent.putExtra("folder_name", "系统工具");
            createFolderIntent.putExtra("target_package", packageName);
            context.sendBroadcast(createFolderIntent);

            return true;
        } catch (Exception e) {
            Log.e(TAG, "Intent method failed", e);
            return false;
        }
    }

    /**
     * 通过无障碍服务移动应用
     */
    private static boolean moveAppViaAccessibility(Context context, String packageName) {
        if (!isAccessibilityServiceEnabled(context)) {
            return false;
        }

        try {
            // 1. 启动Launcher
            Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
            launcherIntent.addCategory(Intent.CATEGORY_HOME);
            launcherIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(launcherIntent);

            // 2. 等待Launcher加载
            Thread.sleep(2000);

            // 3. 通过无障碍服务操作
            AccessibilityOperator.moveAppToFolder(packageName);

            return true;

        } catch (Exception e) {
            Log.e(TAG, "Accessibility operation failed", e);
            return false;
        }
    }

    /**
     * 检查Root权限
     */
    private static boolean hasRootAccess() {
        try {
            Process process = Runtime.getRuntime().exec("su");
            return process.getOutputStream() != null;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查无障碍服务是否启用
     */
    private static boolean isAccessibilityServiceEnabled(Context context) {
        AccessibilityManager am = (AccessibilityManager)
                context.getSystemService(Context.ACCESSIBILITY_SERVICE);

        List<AccessibilityServiceInfo> enabledServices =
                am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);

        String packageName = context.getPackageName();
        for (AccessibilityServiceInfo service : enabledServices) {
            if (service.getResolveInfo().serviceInfo.packageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

}
